package com.zhanghe.study.study_scala.fun

/**
 * PartialFunction 偏函数
 * @author zh
 * @date 2021/5/9 17:02
 */
object TestPartialFunction {
  def main(args: Array[String]): Unit = {

    def partFun  = new PartialFunction[Any,Int] {
      // 进行条件过滤，为true的才会执行apply方法
      override def isDefinedAt(x: Any): Boolean = {
        x.isInstanceOf[Int]
      }

      override def apply(v1: Any): Int = {
        v1.asInstanceOf[Int]*2
      }
    }

    // 偏函数简写
    def partFun1 : PartialFunction[Any,Int] = {
      case a:Int => a*2
    }



    val list = List(1,"a",2.5,4.6f,"b",24)

    val partList = list.collect(partFun)
    // List(2, 48)
    println(partList)

    val partList1 = list.collect(partFun1)
    // List(2, 48)
    println(partList1)
  }
}
